
import {GetMenuList,GetMenuInfoList,GetMenuInfo,AddEditMenuInfo} from '@/api/menu';
import store from '@/store'
import { asyncRouterMap, constantRoutes } from '@/router'

const state = {
    menuList:[]
  }
  
  const mutations = {
    SET_MenuList: (state, menuList) => {
      state.menuList = menuList
    }
  }
  
  const actions = {
    //获取当前用户权限菜单
    getMenuList({ dispatch, commit }){
        return new Promise((resolve, reject) => {
          GetMenuList().then(response => {
              const { data } = response
             console.log('用户当前菜单');
             console.log(response.data);
            let dat=response.data;
            const accessedRouters = constantRoutes.filter(v => {
                    // if (roles.indexOf('admin') >= 0) {
                    //     return true;
                    // };
                    if (hasPermission(dat, v)) {
                        if (v.children && v.children.length > 0) {
                            v.children = v.children.filter(child => {
                                if (hasPermission(dat, child)) {
                                    return child
                                }
                                return false;
                            });
                            return v
                        } else {
                            return v
                        }
                    }
                    return false;
                });

              console.log('过滤之后菜单权限');
              console.log(accessedRouters);
              //设置动态路由 yijing xiugai
             commit('SET_MenuList', accessedRouters)
              resolve(accessedRouters)
            }).catch(error => {
              reject(error)
            })
          })
     },
     //菜单列表
     GetMenuInfoList({commit,state},data){
      return new Promise((resolve, reject) => {
        GetMenuInfoList(data).then(response => {
            const { data } = response
            resolve(data)
          })
        })
      },
    //菜单详情
     GetMenuInfo({commit,state},data){
      return new Promise((resolve, reject) => {
        GetMenuInfo(data).then(response => {
            const { data } = response
            resolve(data)
          })
        })
      },
      //菜单添加编辑
      AddEditMenuInfo({commit,state},data){
      return new Promise((resolve, reject) => {
        AddEditMenuInfo(data).then(response => {
            const { data } = response
            resolve(data)
          })
        })
      }
  }
//判断是否有权限
function hasPermission(menuList, route) {
    ///公共的
    if(route.meta&&route.meta.permission=="public"){
      return true;
    }
    //后台设置权限判断
    if (route.meta && route.meta.permission) {
        return menuList.some(menu => route.meta.permission.indexOf(menu.customData)>-1);
    } else {
        return true;
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}